import * as Nexus from "@nexus/schema";
import _ from "lodash";
import { fieldName, fieldDescription, inputName, payloadName } from "./config";
import { getRandCharByLen, getSnowflakeId } from "../../../../util/tools";
import { UserInputError } from "apollo-server-koa";

// 拓展类型
export default Nexus.extendType({
  // 类型
  type: "Mutation",

  // 定义
  definition(t) {
    t.field(fieldName, {
      // 描述
      description: fieldDescription,

      // 类型
      type: payloadName,

      // 参数
      args: {
        // 输入
        input: Nexus.nonNull(
          Nexus.arg({
            // 描述
            description: "输入",

            // 类型
            type: inputName,
          }),
        ),
      },

      // 权限认证
      authorize: (_root, _args, ctx, info) => {
        return ctx.service.authenticate.authenticate(info);
      },

      // 解析
      resolve: async (_root, args, ctx, _info) => {
        const { input } = args;
        const { db } = ctx;

        // 解析参数
        const { name, adminAccount, password } = input;

        const id = getSnowflakeId();

        const admin = await db.admin.findUnique({ where: { account: adminAccount } });
        if (admin) {
          throw new UserInputError("账号已存在");
        }

        await db.store.create({
          data: {
            id,
            name,
            adminList: {
              create: {
                name: "管理员",
                account: adminAccount,
                password: ctx.service.encryption.getPasswordHash(password),
              },
            },
          },
        });

        return { code: 0, message: "创建成功", password, appId: id };
      },
    });
  },
});
